package org.geektimes.projects.dependency.servlet;

import org.geektimes.projects.microprofile.servlet.ApplicationContextListener;
import org.geektimes.projects.microprofile.servlet.TestServletContextListener;

import javax.annotation.Priority;
import javax.servlet.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;

/**
 * @author biwin
 */
@Priority(1)
public class RootWebApplicationInitializer implements ServletContainerInitializer, ServletContextListener {

    private static ThreadLocal<ServletContextEvent> ctxThreadLocal = new ThreadLocal<>();

    private static List<ApplicationContextListener> contextListeners = new ArrayList<>();

    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        loadSpi(ApplicationContextListener.class);
        ctxThreadLocal.set(new ServletContextEvent(ctx));
        ServletContext servletContext = getServletContextEvent().getServletContext();
        servletContext.addListener(RootWebApplicationInitializer.class);
    }


    private void loadSpi(Class<ApplicationContextListener> clz) {
        ServiceLoader.load(clz).forEach(contextListeners::add);
        contextListeners.sort(PriorityComparator.INSTANCE);
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        contextListeners.forEach(a -> a.contextInitialized(getServletContextEvent()));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        contextListeners.forEach(a -> a.contextDestroyed(getServletContextEvent()));
    }

    public ServletContextEvent getServletContextEvent() {
        return ctxThreadLocal.get();
    }
}
